package com.example.mydy;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.mydy.api.UserApi;
import com.example.mydy.model.RewardTask;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.utils.NetworkUtils;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.text.SimpleDateFormat;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RewardDetailActivity extends AppCompatActivity {

    private static final String EXTRA_TASK_ID = "task_id";

    private int taskId;
    private RewardTask rewardTask;
    private UserApi userApi;
    private String username;
    private boolean useMockData = true; // 控制是否使用模拟数据

    // UI 组件
    private TextView tvTitle;
    private TextView tvDescription;
    private TextView tvAmount;
    private TextView tvDeadline;
    private TextView tvOrders;
    private TextView tvCreatedAt;
    private Button btnTakeTask;
    private ImageView ivTaskImage;
    private ChipGroup tagGroup;

    /**
     * 创建启动RewardDetailActivity的Intent
     * @param context 上下文
     * @param taskId 任务ID
     * @return Intent实例
     */
    public static Intent createIntent(Context context, int taskId) {
        Intent intent = new Intent(context, RewardDetailActivity.class);
        intent.putExtra(EXTRA_TASK_ID, taskId);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reward_detail);

        // 获取任务ID
        taskId = getIntent().getIntExtra(EXTRA_TASK_ID, -1);
        if (taskId == -1) {
            Toast.makeText(this, "无效的任务ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        userApi = NetworkUtils.getUserApi();
        username = NetworkUtils.getUsername();

        // 初始化UI组件
        initViews();
        setupToolbar();

        // 加载任务详情
        loadRewardDetail();
    }

    private void initViews() {
        tvTitle = findViewById(R.id.tv_reward_detail_title);
        tvDescription = findViewById(R.id.tv_reward_detail_description);
        tvAmount = findViewById(R.id.tv_reward_detail_amount);
        tvDeadline = findViewById(R.id.tv_reward_detail_deadline);
        tvOrders = findViewById(R.id.tv_reward_detail_orders);
        tvCreatedAt = findViewById(R.id.tv_reward_detail_created);
        btnTakeTask = findViewById(R.id.btn_take_reward_detail);
        ivTaskImage = findViewById(R.id.iv_reward_image);
        tagGroup = findViewById(R.id.reward_detail_tag_group);

        // 设置任务接取按钮点击事件
        btnTakeTask.setOnClickListener(v -> takeTask());
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("任务详情");

        toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 分享按钮
        findViewById(R.id.btn_share_reward).setOnClickListener(v -> shareTask());
    }

    private void loadRewardDetail() {
        if (useMockData) {
            MockApiService.getRewardTask(taskId, new Callback<RewardTask>() {
                @Override
                public void onResponse(Call<RewardTask> call, Response<RewardTask> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        rewardTask = response.body();
                        updateUI();
                    } else {
                        Toast.makeText(RewardDetailActivity.this, "获取任务详情失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<RewardTask> call, Throwable t) {
                    Toast.makeText(RewardDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            userApi.getRewardTask(taskId).enqueue(new Callback<RewardTask>() {
                @Override
                public void onResponse(Call<RewardTask> call, Response<RewardTask> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        rewardTask = response.body();
                        updateUI();
                    } else {
                        Toast.makeText(RewardDetailActivity.this, "获取任务详情失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<RewardTask> call, Throwable t) {
                    Toast.makeText(RewardDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void updateUI() {
        // 设置任务标题和描述
        tvTitle.setText(rewardTask.getTitle());
        tvDescription.setText(rewardTask.getDescription());

        // 设置奖励金额
        tvAmount.setText(String.format(Locale.CHINA, "¥%.2f", rewardTask.getReward()));

        // 设置截止日期
        if (rewardTask.getDeadline() != null && !rewardTask.getDeadline().isEmpty()) {
            tvDeadline.setText(formatDate(rewardTask.getDeadline()));
        } else {
            tvDeadline.setText("无限期");
        }

        // 设置剩余名额
        tvOrders.setText(String.valueOf(rewardTask.getRemainingOrders()));

        // 设置创建日期
        if (rewardTask.getCreatedAt() != null && !rewardTask.getCreatedAt().isEmpty()) {
            tvCreatedAt.setText(formatDate(rewardTask.getCreatedAt()));
        } else {
            tvCreatedAt.setText("未知");
        }

        // 设置标签
        tagGroup.removeAllViews();
        if (rewardTask.getTags() != null && !rewardTask.getTags().isEmpty()) {
            for (String tag : rewardTask.getTags()) {
                Chip chip = new Chip(this);
                chip.setText(tag);
                chip.setClickable(false);
                chip.setCheckable(false);
                tagGroup.addView(chip);
            }
        }

        // 设置按钮状态
        if (username != null && username.equals(rewardTask.getUsername())) {
            // 已经接取了该任务
            btnTakeTask.setText("已接取");
            btnTakeTask.setEnabled(false);
        } else if (rewardTask.isTaken()) {
            // 任务已被他人接取
            btnTakeTask.setText("任务已被接取");
            btnTakeTask.setEnabled(false);
        } else if (rewardTask.getRemainingOrders() <= 0) {
            // 任务已满额
            btnTakeTask.setText("任务已满额");
            btnTakeTask.setEnabled(false);
        } else {
            // 可以接取
            btnTakeTask.setText("接取任务");
            btnTakeTask.setEnabled(true);
        }

        // 处理任务图片，如果有的话
        if (rewardTask.getImageUrl() != null && !TextUtils.isEmpty(rewardTask.getImageUrl())) {
            ivTaskImage.setVisibility(View.VISIBLE);
            // 此处应使用图片加载库如Glide或Picasso加载图片
            // 简单示例：
            try {
                byte[] decodedString = Base64.decode(rewardTask.getImageUrl(), Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                ivTaskImage.setImageBitmap(decodedByte);
            } catch (Exception e) {
                ivTaskImage.setVisibility(View.GONE);
            }
        } else {
            ivTaskImage.setVisibility(View.GONE);
        }
    }

    private void takeTask() {
        if (username == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (useMockData) {
            MockApiService.takeRewardTask(username, taskId, new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(RewardDetailActivity.this, "接取任务成功", Toast.LENGTH_SHORT).show();
                        // 重新加载任务详情
                        loadRewardDetail();
                    } else {
                        String errorMsg = response.body() != null ? response.body().getMessage() : "接取任务失败";
                        Toast.makeText(RewardDetailActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Toast.makeText(RewardDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            userApi.takeRewardTask(username, taskId).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        CommonResponse commonResponse = response.body();
                        if (commonResponse.isSuccess()) {
                            Toast.makeText(RewardDetailActivity.this, "领取成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(RewardDetailActivity.this, commonResponse.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(RewardDetailActivity.this, "领取失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Toast.makeText(RewardDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void shareTask() {
        if (rewardTask == null) return;

        String shareText = String.format("【悬赏任务】%s\n奖励: ¥%.2f\n%s",
                rewardTask.getTitle(),
                rewardTask.getReward(),
                rewardTask.getDescription());

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        shareIntent.setType("text/plain");

        startActivity(Intent.createChooser(shareIntent, "分享任务"));
    }

    private String formatDate(String dateString) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            return outputFormat.format(inputFormat.parse(dateString));
        } catch (Exception e) {
            return dateString;
        }
    }
} 